package ez

import (
	"log"
	"path"
	"runtime"
)

const (
	LoggerTypeFile    = "file"
	LoggerTypeConsole = "console"
	LoggerTypeMq      = "nsq"
	LoggerTypeNone    = "none"
)

type Logger struct {
	Type string //默认写入文件
	clog *ConsoleLogger
	flog *FileLogger
	qlog *MqLogger

	//配置
	//-文件日志
	FilePath string
	//mq日志
	NsqPubAddr string
	Depth      int
	DepthSkip  int
}

var logger *Logger

func CreateLogger() *Logger {
	logger = &Logger{
		Type:     LoggerTypeConsole,
		FilePath: "./var/logs/orm.log",
	}
	return logger
}

func (this *Logger) UseNoLogger() {
	this.Type = LoggerTypeNone
}

func (this *Logger) InitFileLogger() {
	//初始化文件日志
	fl := &FileLogger{
		Root:     path.Dir(this.FilePath),
		FilePath: this.FilePath,
		MaxSize:  2 * 1024,
		MaxLine:  10000,
	}
	fl.Logger = log.New(fl.CreateNewFile(), "[EZ]", log.LstdFlags)
	this.flog = fl
}
func (this *Logger) UseFileLogger() {
	this.Type = LoggerTypeFile
}
func (this *Logger) GetFileLogger() *FileLogger {
	return this.flog
}

func (this *Logger) InitConsoleLogger() {
	//初始化Console日志
	this.clog = NewConsoleLogger()
}
func (this *Logger) UseConsoleLogger() {
	this.Type = LoggerTypeConsole
}
func (this *Logger) GetConsoleLogger() *ConsoleLogger {
	return this.clog
}

func (this *Logger) InitMqLogger() {
	//初始化Nsq日志
	this.qlog = NewMqLogger(this.NsqPubAddr)
}
func (this *Logger) UseMqLogger() {
	this.Type = LoggerTypeMq
}
func (this *Logger) GetMqLogger() *MqLogger {
	return this.qlog
}

func (this *Logger) Printf(format string, v ...interface{}) {
	//调用链跟踪
	pc, f, l, _ := runtime.Caller(5)

	switch this.Type {
	case LoggerTypeMq:
		if this.qlog == nil {
			this.clog.Printf("%s:%d %s", f, l, runtime.FuncForPC(pc).Name())
			this.clog.Printf(format, v...)
		} else {
			this.qlog.Printf("%s:%d %s", f, l, runtime.FuncForPC(pc).Name())
			this.qlog.Printf(format, v...)
		}
	case LoggerTypeConsole:
		this.clog.Printf("%s:%d %s", f, l, runtime.FuncForPC(pc).Name())
		this.clog.Printf(format, v...)
	case LoggerTypeFile:
		this.flog.Printf("%s:%d %s", f, l, runtime.FuncForPC(pc).Name())
		this.flog.Printf(format, v...)
	default:
		//不输出
	}
}
